package org.mzx.shortLink.VIP.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jodd.util.StringUtil;
import lombok.RequiredArgsConstructor;
import org.mzx.shortLink.VIP.domain.TVip;
import org.mzx.shortLink.VIP.dto.request.payVipOrRenewalReq;
import org.mzx.shortLink.VIP.service.TVipService;
import org.mzx.shortLink.VIP.mapper.TVipMapper;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

import static org.mzx.shortLink.VIP.common.Enum.redisEnum.VIP_CHECK_KEY;

/**
* @author 22701
* @description 针对表【t_vip】的数据库操作Service实现
* @createDate 2025-04-27 15:29:04
*/
@Service
@RequiredArgsConstructor
public class TVipServiceImpl extends ServiceImpl<TVipMapper, TVip>
    implements TVipService{

    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public void payVipOrRenewal(payVipOrRenewalReq requestParam) {
        //首先查询是否已经是会员
        TVip vip = lambdaQuery().eq(TVip::getUsername, requestParam.getUsername())
                .one();
        Long time = requestParam.getDuration() * 3600 * 1000;
        //如果原本不是会员的话，那么创建一个会员记录
        if(vip == null){
            Date date = new Date(System.currentTimeMillis() + time);
            vip = TVip.builder()
                    .expiryDate(date)
                    .username(requestParam.getUsername())
                    .build();
        }else {
            //是会员那么就续费
            vip.setExpiryDate(new Date(vip.getExpiryDate().getTime()+time));
        }
        //写入数据库
        saveOrUpdate(vip);

    }

    /**
     * 先写一个简单实现！！！
     * @param userName
     * @return
     */
    @Override
    public Boolean check(String userName) {

        //优先查缓存=====》会在登陆中写入缓存
        String s = stringRedisTemplate.opsForValue().get(VIP_CHECK_KEY + userName);
        if(StringUtil.isNotEmpty(s)){
            return true;
        }

        //如果缓存中没有，那么查询数据库
        TVip vip = lambdaQuery()
                .eq(TVip::getUsername, userName)
                .one();
        return vip!=null;
    }

}




